//
//  RYSwitchCell.swift
//  App_Profile
//
//  Created by 蒋晨成 on 2022/2/9.
//

import Foundation
import UIKit

public class RYSwitchCell: RYTitleCell {
    lazy var switchView: UISwitch = .init()
        .x
        .addTarget(self, action: #selector(switchValueChanged(switchItem:)), for: .valueChanged)
        .instance

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") }

    override func reusableCell(_ cellModel: RYBaseCellModel) {
        super.reusableCell(cellModel)
        guard let cellModel = cellModel as? RYSwitchCellModel else { return }
        switchView.isOn = cellModel.isOn
    }
}

private extension RYSwitchCell {
    func setupUI() {
        switchView.x.add(to: contentView).snp.makeConstraints {
            $0.trailing.equalToSuperview().offset(-20)
            $0.centerY.equalToSuperview()
        }
    }

    @objc
    func switchValueChanged(switchItem: UISwitch) {
        guard let cellModel = cellModel as? RYSwitchCellModel else { return }
        cellModel.isOn = switchItem.isOn
        cellModel.switchAction?(cellModel, switchItem.isOn)
    }
}
